<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card" v-if="!addshow && !edshow">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="title" label="标题">
                  <a-input
                    v-model="formModel.title"
                    placeholder="请输入标题"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="nickname" label="用户类型">
                  <a-select
                    v-model="formModel.userType"
                    placeholder="请选择用户类型"
                    allow-clear
                  >
                    <a-option
                      v-for="item of userTypes"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                  <a-button type="primary" @click="add">
                    <template #icon>
                      <icon-plus />
                    </template>
                    新增
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <a-table
        ref="userList"
        row-key="userId"
        v-model:selectedKeys="userIds"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :row-selection="rowSelection"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="primary">
              查看详情
            </a-button>
            <a-button
              status="danger"
              @click="openDelete(record)"
              v-if="record.username != 'admin'"
            >
              删除
            </a-button>
          </a-space>
        </template>
        <template #addresseeUserType="{ record }">
          {{ getAppointmentTypes(record.addresseeUserType) }}
        </template>
        <template #type="{ record }">
          {{ record.type == 'SYSTEM' ? '系统内部' : '公开' }}
        </template>

        <!-- <template #content="{ record }" class="contentgl">
          <div> {{ record.content }}</div>
        </template> -->
      </a-table>
    </a-card>
    <a-card title="新增通知公告" v-if="addshow">
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="title" label="通知标题:">
              <a-input
                v-model="addForm.title"
                size="large"
                placeholder="请输入10字以内的标题"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="content" label="通知内容:">
              <a-textarea
                class="wbygd"
                placeholder="请输入100字内的内容"
                allow-clear
                v-model="addForm.content"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="addresseeUserType" label="接收用户:">
              <a-col :span="4">
                <a-checkbox
                  :model-value="checkedAll"
                  :indeterminate="indeterminate"
                  @change="handleChangeAll"
                  >全选
                </a-checkbox></a-col
              >

              <a-checkbox-group
                v-model="addresseeUserTypedata"
                @change="handleChange"
              >
                <a-checkbox value="TEACHER">老师</a-checkbox>
                <a-checkbox value="STUDENT">学生</a-checkbox>
                <a-checkbox value="VISITOR">访客</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="type" label="公告类型:">
              <!-- <a-radio-group>
                <a-radio value="A">A</a-radio>
                <a-radio value="A">A</a-radio>
              </a-radio-group> -->
              <a-checkbox-group
                v-model="addForm.type"
                @change="handleChanges"
                :max="1"
              >
                <a-checkbox value="SYSTEM">系统内部</a-checkbox>
                <a-checkbox value="PUBLIC">公开</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="20">
            <div class="addmens">
              <a-button @click="back">返回</a-button>
              <a-button type="primary" @click="saveadd">保存</a-button>
            </div></a-col
          >
        </a-row>
      </a-form>
    </a-card>
    <a-card title="通知公告内容" v-if="edshow">
      <a-form ref="addModel" :model="addForm">
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="title" label="通知标题:">
              {{ addForm.title }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="content" label="通知内容:">
              {{ addForm.content }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="createTime" label="发送时间:">
              {{ addForm.createTime }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="addresseeUserType" label="用户类型:">
              {{ getAppointmentTypes(addForm.addresseeUserType) }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="20">
            <div class="addmens">
              <a-button @click="backs">返回</a-button>
              <a-button type="primary" @click="openDeletes(addForm.notifyId)"
                >删除</a-button
              >
            </div></a-col
          >
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import useLoading from '@/hooks/loading';

  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';

  import { addNotify, notifyList, notifyRemove } from '@/api/notice';

  const { loading, setLoading } = useLoading(true);

  const addshow = ref(false);
  const edshow = ref(false);

  //   查看详情
  const openEdit = (item) => {
    console.log('查看详情', item);
    addForm.addresseeUserType = item.addresseeUserType;
    addForm.content = item.content;
    addForm.title = item.title;
    addForm.createTime = item.createTime;
    addForm.notifyId = item.notifyId;
    edshow.value = true;
  };
  //   添加
  const saveadd = () => {
    //先验证表单是否通过
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        // 验证通过的情况下 请求接口
        if (!errors) {
          addNotify({
            addresseeUserType: addForm.addresseeUserType,
            content: addForm.content,
            title: addForm.title,
            type: addForm.type.toString(),
          }).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '发布成功',
              });
              restaddForm();
              fetchData();
              addshow.value = false;
            } else {
            }
          });
        }
      }
    );
  };
  // 清空表单
  const restaddForm = () => {
    addForm.title = '';
    addForm.content = '';
    addForm.addresseeUserType = '';
    addForm.createTime = '';
    addForm.type = '';
    addresseeUserTypedata.value = [];
    checkedAll.value = false;
  };
  //   返回

  const back = () => {
    restaddForm();
    addshow.value = false;
    fetchData();
  };
  const backs = () => {
    restaddForm();
    edshow.value = false;
    fetchData();
  };
  //   处理多选 全选相关逻辑
  const indeterminate = ref(false);
  const checkedAll = ref(false);
  const addresseeUserTypedata = ref([]);

  const handleChangeAll = (value) => {
    indeterminate.value = false;
    if (value) {
      checkedAll.value = true;
      addresseeUserTypedata.value = ['TEACHER', 'STUDENT', 'VISITOR'];
      addForm.addresseeUserType = addresseeUserTypedata.value.join(',');
      //   console.log('addForm.addresseeUserType', addForm.addresseeUserType);
    } else {
      checkedAll.value = false;
      addresseeUserTypedata.value = [];
      addForm.addresseeUserType = '';
      if (addForm.type == 'PUBLIC') {
        addForm.type = '';
      }
    }
  };

  const handleChange = (values) => {
    // console.log('非全选', values);
    addForm.addresseeUserType = values.join(',');
    // console.log('addForm.addresseeUserType', addForm.addresseeUserType);
    if (values.length === 3) {
      checkedAll.value = true;
      indeterminate.value = false;
    } else if (values.length === 0) {
      checkedAll.value = false;
      indeterminate.value = false;
    } else {
      checkedAll.value = false;
      indeterminate.value = true;
      if (addForm.type == 'PUBLIC') {
        addForm.type = '';
      }
    }
  };
  const handleChanges = (values) => {
    if (values == 'PUBLIC') {
      checkedAll.value = true;
      handleChangeAll(true);
    }
  };
  //   初始化表单
  const addForm = reactive({
    title: '',
    content: '',
    addresseeUserType: '',
    createTime: '',
    type: '',
  });
  //   表单验证规则
  const rules = reactive({
    title: [
      {
        required: true,
        message: '请输入10字内的标题',
        maxLength: '10',
      },
    ],
    content: [
      {
        required: true,
        message: '请输入100字内的内容',
        maxLength: '100',
      },
    ],
    addresseeUserType: [
      {
        required: true,
        message: '请选择接收人类型',
      },
    ],
    type: [
      {
        required: true,
        message: '请选择接公告类型',
      },
    ],
  });
  //   新增
  const add = () => {
    addshow.value = true;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        notifyRemove({
          notifyId: item.notifyId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };
  const openDeletes = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        notifyRemove({
          notifyId: item,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
            edshow.value = false;
          }
        });
      },
    });
  };

  const userIds = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'notifyId',
    },
    {
      title: '标题',
      dataIndex: 'title',
    },

    {
      title: '内容概要',
      dataIndex: 'content',
      ellipsis: 'true',
      //   slots: 'content',
    },

    {
      title: '发送时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '推送用户类型',
      dataIndex: 'addresseeUserType',
      slotName: 'addresseeUserType',
      align: 'center',
    },
    {
      title: '公告类型',
      dataIndex: 'type',
      slotName: 'type',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);
  const userTypes = reactive([
    { id: 'TEACHER', name: '老师' },
    { id: 'STUDENT', name: '学生' },
    { id: 'VISITOR', name: '访客' },
  ]);
  const generateFormModel = () => {
    return {
      title: '',
      userType: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    // 'hide-on-single-page': true,
    // 'show-total': true,
    // 'show-jumper': true,
    // 'show-page-size': true,
  });
  // 处理 openAppointment 字段，将英文状态转换为中文
  const getAppointmentTypes = (openAppointment: string) => {
    const types = openAppointment.split(','); // 将字符串按逗号分割成数组
    return types.map((type: string) => getAppointmentType(type)).join(', '); // 调用 getAppointmentType 转换为中文后再连接成字符串
  };
  const getAppointmentType = (type: string): string => {
    switch (type) {
      case 'TEACHER':
        return '老师';
      case 'STUDENT':
        return '学生';
      case 'VISITOR':
        return '访客';
      default:
        return '';
    }
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      notifyList(data).then((res) => {
        let list = res.data.list || [];
        list.map((item) => {
          item.disabled = item.isLocking == 1 ? false : true;
        });
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  fetchData();
  const addModel = ref();
</script>
<style>
  .wbygd {
    height: 200px;
  }
  .addmens {
    /* position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); */
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .addmens button {
    margin: 10px 20px;
  }
</style>
